package zhtt.example.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.session.CookieWebSessionIdResolver;
import org.springframework.web.server.session.WebSessionIdResolver;

import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Created by zhaoq on   2024/7/23 16:35
 **/
@Slf4j
@Configuration
//@EnableRedisWebSession// 用于处理cookie加密
public class WebSessionConfig {
    @Bean
    public WebSessionIdResolver webSessionIdResolver() {
        return new CustomWebSessionIdResolver();
    }

    private static class CustomWebSessionIdResolver extends CookieWebSessionIdResolver {

        @Override
        public void setSessionId(ServerWebExchange exchange, String id) {
            super.setSessionId(exchange, base64Encode(id));
        }

        @Override
        public List<String> resolveSessionIds(ServerWebExchange exchange) {
            List<String> strings = super.resolveSessionIds(exchange);
            return strings.stream().map(this::base64Decode).collect(Collectors.toList());
        }

        @Override
        public void expireSession(ServerWebExchange exchange) {
            super.expireSession(exchange);
        }

        private String base64Encode(String value) {
            try {
                return Base64.getEncoder().encodeToString(value.getBytes(StandardCharsets.UTF_8));
            } catch (Exception ex) {
                ex.printStackTrace();
                return value;
            }
        }

        private String base64Decode(String value) {
            try {
                byte[] decodedCookieBytes = Base64.getDecoder().decode(value);
                return new String(decodedCookieBytes);
            } catch (Exception ex) {
                return value;
            }
        }
    }
}
